// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.

#include "UEOpenSSLTestCharacter.h"
#include "HeadMountedDisplayFunctionLibrary.h"
#include "Camera/CameraComponent.h"
#include "Components/CapsuleComponent.h"
#include "Components/InputComponent.h"
#include "GameFramework/CharacterMovementComponent.h"
#include "GameFramework/Controller.h"
#include "GameFramework/SpringArmComponent.h"
#include "Misc/Base64.h"

DEFINE_LOG_CATEGORY(Ekko);

//////////////////////////////////////////////////////////////////////////
// AUEOpenSSLTestCharacter

AUEOpenSSLTestCharacter::AUEOpenSSLTestCharacter()
{
	TArray<uint8> PublicModulusUint8s, PublicExponentUint8s;
	FString PublicModulus64 = "AIu0+SZdBrZr2T5znwXJ0I/SpyntlETpuBrf//4WAMtz0hrYDa+6iD9XhLWcyccjPqs47UGwbDskaGFmS+tEmi7NRQgD3+A/suVfJgaAhWIpk0b2KthG1kTGtMUQF+L8i6AWBnGesAOYryEhVMOukKDlsENpHAzf4ln2SA4EQCKl";
	FString PublicExponent64 = "AQAB";
	FBase64::Decode(PublicModulus64, PublicModulusUint8s);
	FBase64::Decode(PublicExponent64, PublicExponentUint8s);
	unsigned char *pPublicModulusBin = new unsigned char[PublicModulusUint8s.Num()];
	unsigned char *pPublicExponentBin = new unsigned char[PublicExponentUint8s.Num()];
	for (int32 i = 0; i < PublicModulusUint8s.Num(); ++i)
	{
		pPublicModulusBin[i] = PublicModulusUint8s[i];
	}
	for (int32 i = 0; i < PublicExponentUint8s.Num(); ++i)
	{
		pPublicExponentBin[i] = PublicExponentUint8s[i];
	}
	RSA *PublicRSA = RSA_new();
	PublicRSA->n = BN_bin2bn(pPublicModulusBin, PublicModulusUint8s.Num(), nullptr);
	PublicRSA->e = BN_bin2bn(pPublicExponentBin, PublicExponentUint8s.Num(), nullptr);
	const char *Msg = "nihaoa";
	int32 EncryptMsgLen = RSA_size(PublicRSA);
	unsigned char *EncryptMsg = new unsigned char[EncryptMsgLen];
	FMemory::Memset(EncryptMsg, 0, EncryptMsgLen);
	if (RSA_public_encrypt(strlen(Msg), (const unsigned char *)Msg, EncryptMsg, PublicRSA, RSA_PKCS1_PADDING) >= 0)
	{
		UE_LOG(Ekko, Log, TEXT("RSA_public_encrypt Msg:%s"), ANSI_TO_TCHAR(Msg));
		UE_LOG(Ekko, Log, TEXT("RSA_public_encrypt EncryptMsg:%s"), ANSI_TO_TCHAR((char*)EncryptMsg));
	}
	else
	{
		UE_LOG(Ekko, Log, TEXT("RSA_public_encrypt error"));
	}
	delete[]pPublicModulusBin;
	//delete []pPublicExponentBin;
	RSA_free(PublicRSA);


	/////////////////////////////////////
	// decode
	TArray<uint8> PrivateModulusUint8s, PrivateExponentUint8s;
	FString PrivateModulus64 = "AIu0+SZdBrZr2T5znwXJ0I/SpyntlETpuBrf//4WAMtz0hrYDa+6iD9XhLWcyccjPqs47UGwbDskaGFmS+tEmi7NRQgD3+A/suVfJgaAhWIpk0b2KthG1kTGtMUQF+L8i6AWBnGesAOYryEhVMOukKDlsENpHAzf4ln2SA4EQCKl";
	FString PrivateExponent64 = "eh444uXR5kcjYEmkqWSdX/pckHPRdONvQF6o36rQCwc0kq5kWEUOr3+Ky00/u0f9kaFzEkZqdNAARZMrrX0L365o32W01+ifPKXefUGejFXdoOWQ8pZT1/vS4C4R6jgFfRoR+p67dpLFJTHinWf9Pd88LyH6etAWHBdH3sNfl0k=";
	FBase64::Decode(PrivateModulus64, PrivateModulusUint8s);
	FBase64::Decode(PrivateExponent64, PrivateExponentUint8s);
	unsigned char *pPrivateModulusBin = new unsigned char[PrivateModulusUint8s.Num()];
	unsigned char *pPrivateExponentBin = new unsigned char[PrivateExponentUint8s.Num()];
	for (int32 i = 0; i < PrivateModulusUint8s.Num(); ++i)
	{
		pPrivateModulusBin[i] = PrivateModulusUint8s[i];
	}
	for (int32 i = 0; i < PrivateExponentUint8s.Num(); ++i)
	{
		pPrivateExponentBin[i] = PrivateExponentUint8s[i];
	}
	RSA *PrivatecRSA = RSA_new();
	PrivatecRSA->n = BN_bin2bn(pPrivateModulusBin, PrivateModulusUint8s.Num(), nullptr);
	PrivatecRSA->e = BN_bin2bn(pPublicExponentBin, PublicExponentUint8s.Num(), nullptr);
	PrivatecRSA->d = BN_bin2bn(pPrivateExponentBin, PrivateExponentUint8s.Num(), nullptr);
	int32 DecryptMsgLen = RSA_size(PrivatecRSA);
	unsigned char *DecryptMsg = new unsigned char[DecryptMsgLen];
	FMemory::Memset(DecryptMsg, 0, DecryptMsgLen);
	if (RSA_private_decrypt(EncryptMsgLen, EncryptMsg, DecryptMsg, PrivatecRSA, RSA_PKCS1_PADDING) >= 0)
	{
		UE_LOG(Ekko, Log, TEXT("RSA_private_decrypt decryptMsg:%s"), ANSI_TO_TCHAR((char*)DecryptMsg));
	}
	else
	{
		UE_LOG(Ekko, Log, TEXT("RSA_private_decrypt error"));
	}
	delete[]EncryptMsg;
	delete[]DecryptMsg;
	delete[]pPrivateModulusBin;
	delete[]pPrivateExponentBin;
	RSA_free(PrivatecRSA);

	// Set size for collision capsule
	GetCapsuleComponent()->InitCapsuleSize(42.f, 96.0f);

	// set our turn rates for input
	BaseTurnRate = 45.f;
	BaseLookUpRate = 45.f;

	// Don't rotate when the controller rotates. Let that just affect the camera.
	bUseControllerRotationPitch = false;
	bUseControllerRotationYaw = false;
	bUseControllerRotationRoll = false;

	// Configure character movement
	GetCharacterMovement()->bOrientRotationToMovement = true; // Character moves in the direction of input...	
	GetCharacterMovement()->RotationRate = FRotator(0.0f, 540.0f, 0.0f); // ...at this rotation rate
	GetCharacterMovement()->JumpZVelocity = 600.f;
	GetCharacterMovement()->AirControl = 0.2f;

	// Create a camera boom (pulls in towards the player if there is a collision)
	CameraBoom = CreateDefaultSubobject<USpringArmComponent>(TEXT("CameraBoom"));
	CameraBoom->SetupAttachment(RootComponent);
	CameraBoom->TargetArmLength = 300.0f; // The camera follows at this distance behind the character	
	CameraBoom->bUsePawnControlRotation = true; // Rotate the arm based on the controller

	// Create a follow camera
	FollowCamera = CreateDefaultSubobject<UCameraComponent>(TEXT("FollowCamera"));
	FollowCamera->SetupAttachment(CameraBoom, USpringArmComponent::SocketName); // Attach the camera to the end of the boom and let the boom adjust to match the controller orientation
	FollowCamera->bUsePawnControlRotation = false; // Camera does not rotate relative to arm

	// Note: The skeletal mesh and anim blueprint references on the Mesh component (inherited from Character) 
	// are set in the derived blueprint asset named MyCharacter (to avoid direct content references in C++)
}

//////////////////////////////////////////////////////////////////////////
// Input

void AUEOpenSSLTestCharacter::SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent)
{
	// Set up gameplay key bindings
	check(PlayerInputComponent);
	PlayerInputComponent->BindAction("Jump", IE_Pressed, this, &ACharacter::Jump);
	PlayerInputComponent->BindAction("Jump", IE_Released, this, &ACharacter::StopJumping);

	PlayerInputComponent->BindAxis("MoveForward", this, &AUEOpenSSLTestCharacter::MoveForward);
	PlayerInputComponent->BindAxis("MoveRight", this, &AUEOpenSSLTestCharacter::MoveRight);

	// We have 2 versions of the rotation bindings to handle different kinds of devices differently
	// "turn" handles devices that provide an absolute delta, such as a mouse.
	// "turnrate" is for devices that we choose to treat as a rate of change, such as an analog joystick
	PlayerInputComponent->BindAxis("Turn", this, &APawn::AddControllerYawInput);
	PlayerInputComponent->BindAxis("TurnRate", this, &AUEOpenSSLTestCharacter::TurnAtRate);
	PlayerInputComponent->BindAxis("LookUp", this, &APawn::AddControllerPitchInput);
	PlayerInputComponent->BindAxis("LookUpRate", this, &AUEOpenSSLTestCharacter::LookUpAtRate);

	// handle touch devices
	PlayerInputComponent->BindTouch(IE_Pressed, this, &AUEOpenSSLTestCharacter::TouchStarted);
	PlayerInputComponent->BindTouch(IE_Released, this, &AUEOpenSSLTestCharacter::TouchStopped);

	// VR headset functionality
	PlayerInputComponent->BindAction("ResetVR", IE_Pressed, this, &AUEOpenSSLTestCharacter::OnResetVR);
}


void AUEOpenSSLTestCharacter::OnResetVR()
{
	UHeadMountedDisplayFunctionLibrary::ResetOrientationAndPosition();
}

void AUEOpenSSLTestCharacter::TouchStarted(ETouchIndex::Type FingerIndex, FVector Location)
{
		Jump();
}

void AUEOpenSSLTestCharacter::TouchStopped(ETouchIndex::Type FingerIndex, FVector Location)
{
		StopJumping();
}

void AUEOpenSSLTestCharacter::TurnAtRate(float Rate)
{
	// calculate delta for this frame from the rate information
	AddControllerYawInput(Rate * BaseTurnRate * GetWorld()->GetDeltaSeconds());
}

void AUEOpenSSLTestCharacter::LookUpAtRate(float Rate)
{
	// calculate delta for this frame from the rate information
	AddControllerPitchInput(Rate * BaseLookUpRate * GetWorld()->GetDeltaSeconds());
}

void AUEOpenSSLTestCharacter::MoveForward(float Value)
{
	if ((Controller != NULL) && (Value != 0.0f))
	{
		// find out which way is forward
		const FRotator Rotation = Controller->GetControlRotation();
		const FRotator YawRotation(0, Rotation.Yaw, 0);

		// get forward vector
		const FVector Direction = FRotationMatrix(YawRotation).GetUnitAxis(EAxis::X);
		AddMovementInput(Direction, Value);
	}
}

void AUEOpenSSLTestCharacter::MoveRight(float Value)
{
	if ( (Controller != NULL) && (Value != 0.0f) )
	{
		// find out which way is right
		const FRotator Rotation = Controller->GetControlRotation();
		const FRotator YawRotation(0, Rotation.Yaw, 0);
	
		// get right vector 
		const FVector Direction = FRotationMatrix(YawRotation).GetUnitAxis(EAxis::Y);
		// add movement in that direction
		AddMovementInput(Direction, Value);
	}
}
